﻿

using System;
using System.Configuration;
using System.Linq;
using MQTTnet;
using MQTTnet.Client;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace WpfClient
{
    /// <summary>
    /// MQTT 消息
    /// </summary>
    public class MQTTServer
    {
        private static MQTTServer _instance;
        private IMqttClient _client;
        string ServerUri = "127.0.0.1";
        string CurrentTopic = null;
        int ServerPort = 10086;
        string ClientID = Guid.NewGuid().ToString("N");
        private byte[] _password = Encoding.UTF8.GetBytes("123456");
        private string _userName = "admin";
        private MQTTServer()
        {
            try
            {
                InitClient();
            }
            catch (Exception)
            {
              //  LogHelper.GetLog().Error("初始化MQTT失败！");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static MQTTServer GetInstance()
        {
            if (_instance == null)
            {
                _instance = new MQTTServer();
            }

            return _instance;
        }
        private void InitClient()
        {
            var options = new MqttClientOptions()
            {
                ClientId = ClientID
            };
            options.ChannelOptions = new MqttClientTcpOptions()
            {
                Server = ServerUri,
                Port = ServerPort
            };
           
            options.Credentials = new MqttClientCredentials(_userName, _password);
            options.CleanSession = true;
            options.KeepAlivePeriod = TimeSpan.FromSeconds(100);
            options.KeepAlivePeriod = TimeSpan.FromSeconds(5);
            if (_client != null)
            {
                _client.DisconnectAsync();
                _client = null;
            }
            _client = new MQTTnet.MqttFactory().CreateMqttClient();

            _client.ConnectedAsync += MqttClient_ConnectedAsync;
            _client.DisconnectedAsync += MqttClient_DisconnectedAsync;
            _client.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
            _client.ConnectAsync(options);
        }


        private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            throw new NotImplementedException();
        }

        private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            throw new NotImplementedException();
        }

        private Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
            throw new NotImplementedException();
        }
       

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        public void SendMessage(MessageInfo msg)
        {
            if (_client != null)
            {
                string topic = msg.FromUserId;
                string content = msg.MessageBody;
                MqttApplicationMessage mqmsg = new MqttApplicationMessage
                {
                    Topic = topic,
                    Payload = Encoding.UTF8.GetBytes(content),
                    QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce,
                    Retain = false
                };
                _client.PublishAsync(mqmsg);
            }
        }
    }
}